<template>
  <d2-container type="card">
    <h3 style="display: inline-block;margin-right: 30px">出勤报表</h3>

     <el-dialog
                title="导出全校个人出勤记录"
                :visible.sync="showExcel"
                width="400px">
            <el-form :inline="true"  >
                <el-form-item>
                    月份：
                <el-date-picker
                        v-model="month"
                        type="month"
                        placeholder="选择月份"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>

          
            
                    
            </el-form>
            
            <div style="width: 100%;text-align: right">
            <el-button @click="showExcel = false">
                取消
            </el-button>
            <el-button @click="exportAll" type='primary'>
                导出
            </el-button>
        </div>
            
        </el-dialog> 

    <el-button type="primary" @click="exportDetail">
                <d2-icon name="download"/>
                导出明细
            </el-button>
            <el-button type="primary" @click="exportExcel">
                <d2-icon name="download"/>
                导出 Excel
            </el-button>
            <el-button type="primary" @click="showExcel = true" v-if="!teacher">
                <d2-icon name="download"/>
                导出个人出勤记录
            </el-button>
    <el-form :inline="true">
      <el-form-item>
        <div class="block">
          <span class="demonstration" style="margin-right:5px">请选择起始日期</span>
          <el-date-picker
            v-model="selectDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </div>
      </el-form-item>
      <el-form-item v-if="!teacher">
        <el-select
          v-model="staffPicked"
          filterable
          placeholder="员工"
        >
          <el-option
            v-for="item in staffList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style='width:150px'>
      <el-select
                            v-model="queryOption.period"
                            >
                        <el-option
                                v-for="item in filterType"
                                :label="item.name"
                                :value="item.value"
                        ></el-option>
                    </el-select>
                    </el-form-item>
      <el-form-item>
        <el-select
          v-model="school"
          filterable
          placeholder="所属校区"
          @change="schoolSelected"
          v-if="headquarter"
        >
          <el-option
            v-for="item in schoolList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="formSubmit">
          <d2-icon name="search" />查询
        </el-button>
      </el-form-item>
      <el-form-item style="float:right">
        <!-- <el-button type="primary" @click="changeDisplayType">{{(display == 1) ? '图表' : '表格' }}</el-button> -->
      </el-form-item>
    </el-form>

    <!-- <template slot="header">导出表格</template>
        <div class="d2-mb" style="display: block;width: 100%;position: relative;" >
            <el-button type="primary" @click="exportCsv">
                <d2-icon name="download"/>
                导出 CSV
            </el-button>
            <el-button type="primary" @click="exportExcel">
                <d2-icon name="download"/>
                导出 Excel
            </el-button>
            <el-button type="primary" @click="setYesterday">
                <d2-icon name="download"/>
                昨天
            </el-button>
            <el-button type="primary" @click="setLastMonth">
                <d2-icon name="download"/>
                上个月
            </el-button>
            <el-button type="primary" @click="setLastYear">
                <d2-icon name="download"/>
    </el-button>-->

    <!-- <el-col :span="6" style="float: right"> -->

    <!-- <el-button type="primary" @click="changeDisplayType" style="position:absolute;right:3vw;top:3vw;z-index: 100">
            {{(display == 1) ? '图表' : '表格' }}
    </el-button>-->
    <!-- </el-col> -->

    <!-- </div> -->

    <!-- <el-form :inline="true" :model="queryOption" ref="dataSearch">

    </el-form>-->

<!-- <div style="margin-bottom: 20px" v-show="display == 0">
      <div id="course_income_2" :style="{width: '1200px', height: '400px',color:'#ccc'}">
      </div>
    </div> -->

        <el-table v-bind="table" style="width: 100%" v-if="display==1">
            <el-table-column
                    v-for="(item, index) in table.columns"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label">
            </el-table-column>
            <el-table-column label='操作'>
              <template slot-scope='scope'>
                <el-button v-if='scope.$index != 0' @click='gotodetail(scope.$index)'>详细</el-button>
              </template>
            </el-table-column>
        </el-table>
    <!-- <el-table v-bind="table" style="width: 100%" v-if="display==1">
            <el-table-column
                    v-for="(item, index) in table.columns"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label">
            </el-table-column>
    </el-table>-->
  </d2-container>
</template>

<script>
import request from "@/plugin/axios";
import { mapState } from "vuex";
import echarts from "echarts";
                                    import excel from "@/libs/util.excel"

function getTodayDate() {
  let day1 = new Date();
  let s1 =
    day1.getFullYear() +
    "-" +
    addZero(day1.getMonth() + 1) +
    "-" +
    addZero(day1.getDate());
  //  + ' ' + addZero(day1.getHours()) + ':' + addZero(day1.getMinutes()) + ':00';
  // s1 = '2019-09-21 17:00'
  return s1;
}

function getYesterdayDate() {
  let day1 = new Date();
  day1.setDate(day1.getDate() - 1);
  let s1 =
    day1.getFullYear() +
    "-" +
    addZero(day1.getMonth() + 1) +
    "-" +
    addZero(day1.getDate());
  return s1;
}

function getLastMonthDate() {
  let day1 = new Date();
  day1.setMonth(day1.getMonth() - 1);
  let s1 =
    day1.getFullYear() +
    "-" +
    addZero(day1.getMonth() + 1) +
    "-" +
    addZero(day1.getDate());
  return s1;
}

function getLastYearDate() {
  let day1 = new Date();
  day1.setFullYear(day1.getFullYear() - 1);
  let s1 =
    day1.getFullYear() +
    "-" +
    addZero(day1.getMonth() + 1) +
    "-" +
    addZero(day1.getDate());
  return s1;
}

function addZero(a) {
  return a < 10 ? "0" + a : a;
}

//以下

function getVirtulData() {
  var date = +echarts.number.parseDate("2019-09-01");
  var end = +echarts.number.parseDate("2019-09-31");
  var dayTime = 3600 * 24 * 1000;
  var data = [];
  for (var time = date; time < end; time += dayTime) {
    data.push([
      echarts.format.formatTime("yyyy-MM-dd", time),
      Math.floor(Math.random() * 10000)
    ]);
  }
  return data;
}

// function getPieSeries(chart) {
//   let scatterData = getVirtulData();
//   return echarts.util.map(scatterData, function(item, index) {
//     var center = chart.convertToPixel("calendar", item);
//     return {
//       id: index + "pie",
//       type: "pie",
//       center: center,
//       label: {
//         normal: {
//           formatter: "{c}",
//           position: "inside"
//         }
//       },
//       radius: 30,
//       data: this.workRecordList
//     };
//   });
// }

// function getPieSeriesUpdate(chart) {
//   let scatterData = getVirtulData();
//   return echarts.util.map(scatterData, function(item, index) {
//     var center = chart.convertToPixel("calendar", item);
//     return {
//       id: index + "pie",
//       center: center
//     };
//   });
// }

//以上

export default {
  data() {
    return {
      series:{},
      cellSize: [80, 80],
      pieRadius:30,
      workRecordList: [],
      teacher :false,
      showExcel : false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },

      selectDate: "",
      filename: __filename,
      headquarter: false,
      schoolList: [],
      display: 1,
      month : new Date(),
      staffList : [],
      staffPicked : undefined,
        staff : undefined,
      table: {
        columns: undefined,
        data: undefined,
        size: "mini",
        stripe: true,
        border: true
      },
      detailStaff : undefined,
      plot: {},
      queryOption: {
        start_time: undefined,
        end_time: undefined,
        period : 'day'
      },
      filterType : [{name:'时长：日',value:'day'},{name:'时长：周',value:'week'},{name:'时长：月',value:'month'},{name:'时长：年','value':'year'}],
    };
  },

  computed: {
    ...mapState("d2admin/user", ["info"])
  },

  methods: {
    gotodetail(index){
      let day = this.table.data[index].date
      let path = '/work-record-day?day=' + day + '&school=' + this.school
      if (this.detailStaff != undefined){
        path += '&staff=' + this.detailStaff
      }
      // console.log(this.detailStaff,path)
      this.$router.push({path:path})
    },
    drawLine() {
        let that = this
      // 基于准备好的dom，初始化echarts实例
      let myChart6 = this.$echarts.init(
        document.getElementById("course_income_2")
      );

      // 绘制图表
      myChart6.setOption({
        tooltip: {},
        legend: {
          data: ["正常", "迟到", "早退","缺卡","旷工"],
          bottom: 20
        },

        calendar: {
          top: "middle",
          left: "center",
          orient: "vertical",
          cellSize: this.cellSize,
          yearLabel: {
            show: true,
            textStyle: {
              fontSize: 30
            }
          },
          
          dayLabel: {
            margin: 20,
            firstDay: 1,
            nameMap: [
              "星期日",
              "星期一",
              "星期二",
              "星期三",
              "星期四",
              "星期五",
              "星期六"
            ]
          },
          monthLabel: {
            show: false
          },
          range: ["2019-09"]
        },
        series: [
          {
            id: "label",
            type: "scatter",
            coordinateSystem: "calendar",
            symbolSize: 1,
            label: {
              normal: {
                show: true,
                formatter: function(params) {
                  return echarts.format.formatTime("dd", params.value[0]);
                },
                offset: [
                  -this.cellSize[0] / 2 + 10,
                  -this.cellSize[1] / 2 + 10
                ],
                textStyle: {
                  color: "#000",
                  fontSize: 14
                }
              }
            },
            data: getVirtulData()
          }
        ]
      });

      if (!app.inNode) {
        console.log(that.getPieSeries(myChart6))
        var pieInitialized;
        setTimeout(function() {
          pieInitialized = true;
          myChart6.setOption({
            series: that.getPieSeries(myChart6)
          });
        }, 10);

        app.onresize = function() {
          if (pieInitialized) {
            myChart6.setOption({
              series: that.getPieSeriesUpdate(myChart6)
            });
          }
        };
      }
    },
    formSubmit() {
      this.getWorkRecordList(this.school);
    },

    getWorkRecordList(school) {
      let startDate = this.selectDate[0];
      let endDate = this.selectDate[1];
      let data = {};
      data.start_time = startDate;
      data.end_time = endDate;
      data.school = school;
      data.period = this.queryOption.period
      data.staff = this.staffPicked
      request({
        url: "/data/getschoolWorkRecord",
        method: "post",
        data: data
      }).then(res => {
       if(res.code==200){
        if (this.staffPicked != undefined){
          this.detailStaff = this.staffPicked
        }
                        this.table.data = [{date:'区间总计',discount:res.data.data.map(function(e){return e.discount}).reduce(function(a,b){
                            return a + b}
                        ),
                        
                         actualNumber:res.data.data.map(function(e){return e.actualNumber}).reduce(function(a,b){
                            return a + b}
                        ),
                         supposeNumber:res.data.data.map(function(e){return e.supposeNumber}).reduce(function(a,b){
                            return a + b}
                        ),
                         lateNumber:res.data.data.map(function(e){return e.lateNumber}).reduce(function(a,b){
                            return a + b}
                        ),
                         earlyNumber:res.data.data.map(function(e){return e.earlyNumber}).reduce(function(a,b){
                            return a + b}
                        ),
                         missNumber:res.data.data.map(function(e){return e.missNumber}).reduce(function(a,b){
                            return a + b}
                        ),
                        //  total:res.data.data.map(function(e){return e.actualNumber}).reduce(function(a,b){
                        //     return a + b}
                        // ),
                        //  actualNumber:res.data.data.map(function(e){return e.actualNumber}).reduce(function(a,b){
                        //     return a + b}
                        // ),
                        
                         }]
                        this.table.data = this.table.data.concat(res.data.data)
                        this.table.columns = res.data.columns
                        this.plot.name = []
                        for (var j = 1 ; j < res.data.columns.length ; j++){
                            this.plot.name.push(res.data.columns[j].label)
                        }
                        var bububu = []
                        for (var i = 0 ; i < res.data.data.length ; i++){
                            bububu.push(res.data.data[i])
                        }
                        bububu.sort(function(a,b){return new Date(a.date) - new Date(b.date) })
                        this.plot.date = bububu.map(function(e){return e.date})
                        this.plot.data = []
                        for (var i =0 ; i < this.plot.name.length ; i++){
                            this.plot.data.push({
                                name :res.data.columns[i + 1].label,
                                type : 'bar',
                                // stack : '总量',
                                areaStyle : {},
                                data :bububu.map(function(e){return e[res.data.columns[i + 1].prop]})
                            })
                        }
                        // this.drawLine()

                    }})

    },

 

    exportExcel() {
      excel.export(this.table.columns,this.table.data,'出勤记录表')
      // this.$export
      //   .excel({
      //     columns: this.table.columns,
      //     data: this.table.data,
      //     title: "出勤记录表"
      //   })
      //   .then(() => {
      //     this.$message("导出表格成功");
      //   });
    },
    schoolSelected() {
      // this.getDepartmentList(1, 99999);
      var ob = this.schoolList
        .map(function(e) {
          return e._id;
        })
        .indexOf(this.school);
      this.school = this.schoolList[ob]._id;
      if (this.schoolList[ob]._id == "all") {
        this.getWorkRecordList("all");
        this.getStaffList()
      } else {
        this.getWorkRecordList(this.schoolList[ob]._id);
        this.getStaffList()
      }
      this.staffPicked = undefined
      this.queryStaff =undefined
    },

    changeDisplayType() {
      // this.getDepartmentList(1, 99999);
      this.display = this.display == 0 ? 1 : 0;
      this.drawLine();
    },
    getSchoolList(page, pageSize) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize);
      request({
        url: "/school/getSchoolList",
        method: "post",
        data
      }).then(res => {
        console.log(res);
        // this.school = this.info.school[0]._id
        this.schoolList = [{ name: "全部", _id: "all" }];
        this.schoolList = this.schoolList.concat(res.data.school);
        // 返回数据
      });
    },

    getStaffList(page, pageSize) {
      let data = {};
      (data.page = 1), (data.pageSize = 99999);
      // data.department = this.staffForm.department
      if (this.school == 'all'){
                    data.school = this.schoolList.map(e=>{return e._id})
                    data.school.splice(0,1)
               
      }
      else{
        data.school = this.school
      }
      request({
        url: "/staff/getStaffList",
        method: "post",
        data
      }).then(res => {
        console.log(res,'sssda')
        this.staffList = res.data.staff;
        // 返回数据
      });
    },

    formatDate(date) {
      var xdate = new Date(date);
      var year = xdate.getFullYear();
      var day = xdate.getDate();
      var month = xdate.getMonth();
      var hour = xdate.getHours();
      var minute = xdate.getMinutes();
      return String(year) + "/" + String(month + 1) + "/" + String(day);
      //  + ' ' + String(this.addZeroBefore(hour)) + ':' + String(this.addZeroBefore(minute))
    },

    addZeroBefore(n) {
      return (n < 10 ? "0" : "") + n;
    },
    getPieSeries(chart) {
      let that = this
      let scatterData = getVirtulData();
      return (echarts.util.map(scatterData, function(item, index) {
        var center = chart.convertToPixel("calendar", item);
        // var need = that.workRecordList[index].need
        // var normal = that.workRecordList[index].normal
        // var late = that.workRecordList[index].late
        // var leaveEarly = that.workRecordList[index].leaveEarly
        // var absence = that.workRecordList[index].absence
        // var inschool = that.workRecordList[index].inschool
        // var fieldwork = that.workRecordList[index].fieldwork
        // console.log(need,normal,late,leaveEarly,absence,inschool,fieldwork)
        return {
            id: index + 'pie',
            type: 'pie',
            center: center,
            label: {
                normal: {
                    formatter: '{c}',
                    position: 'inside'
                }
            },
            radius: that.pieRadius,
            // that.workRecordList[0]
            data: [
                
            ]
        };
        // this.series = {
        //   id: index + "pie",
        //   type: "pie",
        //   center: center,
        //   label: {
        //     normal: {
        //       formatter: "{c}",
        //       position: "inside"
        //     }
        //   },
        //   radius: 30,
        //   data: this.workRecordList
        // };
      }));
    },

    getPieSeriesUpdate(chart) {
      let scatterData = getVirtulData();
      return echarts.util.map(scatterData, function(item, index) {
        var center = chart.convertToPixel("calendar", item);
        return {
            id: index + 'pie',
            center: center
        };
        // this.series =  {
        //   id: index + "pie",
        //   type: "pie",
        //   center: center,
        //   label: {
        //     normal: {
        //       formatter: "{c}",
        //       position: "inside"
        //     }
        //   },
        //   radius: 30,
        //   data: this.workRecordList
        // };
      });
    },
    exportDetail(){
      let startDate = this.selectDate[0];
      let endDate = this.selectDate[1];
      
                var data = {start_time: this.queryOption.start_time,end_time: this.queryOption.end_time,school:this.queryOption.school,staff:this.staffPicked}
                data.start_time = startDate;
      data.end_time = endDate;
                if ((this.school != undefined) && (this.school != 'all')){
                    data.school = this.school
                }
                if (this.queryOption.teacher){
                    data.staff = this.staff
                }
                request({
                    url: "/data/getSchoolWorkRecordDetail",
                    method: "post",
                    data:data

                }).then(res => {
                  excel.export(res.data.columns,res.data.data,'考勤记录明细')
                    //  this.$export.excel({
                    //     columns:res.data.columns,
                    //     data:   res.data.data,
                    //     // header: '总校区课程收入',
                    // title : '考勤记录明细'

                    // })
                    //     .then(() => {
                    //         this.$message('导出明细成功')
                    //     })
                })
    },

    exportAll(){
      let data = {}
      data.month = this.month
      data.school = this.school
       request({
                    url: "/workRecord/exportSchoolStaffExcel",
                    method: "post",
                    data:data

                }).then(res => {
                    if (res.code == 200){
                      let merge = []
                      merge.push({s:{r:0,c:0},e:{r:0,c:10}})
                      // merge.push({s:{r:2,c:0},e:{r:res.data[0].data.length - 1,c:0}})
                      let width = []
                      for (var i =0 ; i < res.data[0].data.length;i++){
                        width.push({wch:15})
                      }
                      console.log(res.data)
                      for (var i = 0 ;i < res.data.length ;i++){
                        excel.exportRaw(res.data[i].data,res.data[i].name,merge,width)
                      }
                      
                    }
                })
    }

  },

  created() {
    this.selectDate = [getLastMonthDate(), getTodayDate()];
    this.school = this.info.school[0]._id;
      this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
    if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2))  {
      this.headquarter = true;
      this.getSchoolList(1, 99999);

    }
    this.rights = this.info.rights.map(function(e){return e.name})
            let index1 = this.rights.indexOf('root') != -1
            let index5 = this.rights.indexOf('校长') != -1
            let index6 = this.rights.indexOf('报表中心') != -1
            let index2 = this.rights.indexOf('授课老师') != -1
            let index4 = this.rights.indexOf('教务老师') != -1
            index2 = (index2 || index4)
            index1 = index1 || index5
            index1 = index1 || index6
            let index3 = this.rights.indexOf('行政管理') == -1
            // 
            if ((!index1) && (index2)){
                if (index3){
                    this.teacher = true
                    this.staffPicked = this.staff
                    this.headquarter = false
                }
            }
            if (!this.teacher){
                this.getStaffList(this.school)
            }

            if (this.staff != null){
                this.getWorkRecordList(this.school);
    }
    else{
              this.$alert('','请先绑定员工')
    }

            
  }
};
</script>
<style lang="scss" scoped>
.page {
  .logo {
    width: 120px;
  }
  .btn-group {
    color: $color-text-placehoder;
    font-size: 12px;
    margin-top: 0px;
    margin-bottom: 20px;
    .btn-group__btn {
      color: $color-text-sub;
      &:hover {
        color: $color-text-main;
      }
      &.btn-group__btn--link {
        color: $color-primary;
      }
    }
  }
}
</style>